package com.wsm.common.config;

import com.wsm.common.mapper.CloseDao;
import com.wsm.common.domain.CloseDO;
import com.wsm.common.enums.BaseEnum;
import com.wsm.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @name: CloseConfig
 * @Author: wangshimin
 * @Date: 2020/2/8  13:49
 * @Description:
 */
@Slf4j
@Component
public class CloseConfig {

    @Autowired
    CloseDao closeDao;

    private static Map<String, String> closeMap;

    public boolean getMap(String key) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        if (null == closeMap) {
            closeMap = new HashMap<>();
            findMap(key);
        }
        if (!(closeMap.containsKey(key))) {
            findMap(key);
        }
        String value = closeMap.get(key);
        if (BaseEnum.CLOSE_FLAG.open.getCode().equals(value)) {
            return true;
        }
        return false;
    }

    private synchronized void findMap(String key) {
        if (closeMap.containsKey(key)) {
            return;
        }
        Map<String, Object> map = new HashMap<>(1);
        map.put("model", key);
        List<CloseDO> list = closeDao.list(map);
        if (null != list && list.size() > 0) {
            CloseDO closeDO = list.get(0);
            if (null != closeDO) {
                if (BaseEnum.CLOSE_FLAG.open.getCode().equals(closeDO.getFlag())) {
                    closeMap.put(key, BaseEnum.CLOSE_FLAG.open.getCode());
                    return;
                }
            }
        }
        closeMap.put(key, BaseEnum.CLOSE_FLAG.close.getCode());
    }

    public synchronized void setMap(String key, String value) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        if (null == closeMap) {
            closeMap = new HashMap<>();
        }
        closeMap.put(key, value);
    }

    public synchronized void deleteKey(String key) {
        if (StringUtils.isEmpty(key) || null == closeMap) {
            return;
        }
        if (closeMap.containsKey(key)) {
            closeMap.put(key, BaseEnum.CLOSE_FLAG.close.getCode());
        }
    }
}
